package com.nulstudio.sppm.controller;
import com.nulstudio.sppm.entity.Customer;
import com.nulstudio.sppm.entity.Supplier;
import com.nulstudio.sppm.network.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;


@Controller
@CrossOrigin(origins = "*")
@RequestMapping("/service/customer")
public final class CustomerController {
    private final List<Customer> customerList = new ArrayList<>();

    @RequestMapping("/fetchAll")
    @ResponseBody
    public Result<Customer[]> fetchAll(@RequestBody Request<?> request) {
        final Customer[] customers = new Customer[customerList.size()];
        for (int i = 0; i < customerList.size(); ++i) {
            customers[i] = customerList.get(i);
        }
        return new Result<>(customers);
    }

    @RequestMapping("/createEntry")
    @ResponseBody
    public Result<CreateCustomerResponse> createEntry(@RequestBody Request<CreateCustomerRequest> rawRequest) {
        final CreateCustomerRequest request = rawRequest.getRequest();
        if (customerList.stream().filter(customer -> customer.getName().equals(request.getName()))
                .findFirst().orElse(null) != null) {
            return new Result<>(100, "Fuck");
        }
        final int uid = customerList.isEmpty() ? 1 : customerList.get(customerList.size() - 1).getId() + 1;
        final Customer customer = new Customer(uid, request.getName(), request.getType(),
                request.getPhone(), request.getAddress(), request.getNotes());
        customerList.add(customer);
        return new Result<>(new CreateCustomerResponse(uid));
    }

    @RequestMapping("/modifyEntry")
    @ResponseBody
    public Result<?> modifyEntry(@RequestBody Request<Customer> request) {
        final Customer customer = customerList.stream()
                .filter(item -> item.getId() == request.getRequest().getId())
                .findFirst().orElse(null);
        if (customer == null) {
            return new Result<>(100, "Fuck");
        }
        customerList.remove(customer);
        customerList.add(request.getRequest());
        customerList.sort(Comparator.comparing(Customer::getId));
        return new Result<>();
    }

    @RequestMapping("/deleteEntry")
    @ResponseBody
    public Result<?> deleteEntry(@RequestBody Request<DeleteCustomerRequest> request) {
        final Set<Integer> deleteIds = new HashSet<>(Arrays.asList(request.getRequest().getId()));
        final List<Customer> customers = customerList.stream()
                .filter(item -> !deleteIds.contains(item.getId()))
                .collect(Collectors.toList());
        customerList.clear();
        customerList.addAll(customers);
        return new Result<>();
    }

}
